package org.catpay.modules.sys.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.catpay.modules.sys.form.SysLoginForm;
import org.catpay.modules.sys.service.SysCaptchaService;
import org.catpay.modules.sys.service.SysUserTokenService;
import org.catpay.modules.sys.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;



/**
 * 登录相关
 * 
 */
@RestController
public class SysLoginController extends AbstractController{
	
	
	@Autowired
	private SysCaptchaService sysCaptchaService;
	
	@Autowired
	private SysUserTokenService sysUserTokenService;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);
		
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public R<?> login(@RequestBody @Validated SysLoginForm form)throws IOException {
		sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(), form.getPassword());
		subject.login(token);
		return sysUserTokenService.createToken();
	}


	@PostMapping("/sys/logout")
	public R<?> logout() {
	//	sysUserTokenService.logout(String.valueOf(getUserId()));
		org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return R.ok();
	}
	
}
